﻿using AutoMapper;
using MediatR;
using WeatherHistory.Data.Repositories.Interfaces;
using WeatherHistory.Shared.Exceptions;

namespace WeatherHistory.Api.CommandsQueries.Commands.Weathers.Delete;

public class DeleteWeathersCommandHandler : IRequestHandler<DeleteWeathersCommandRequest>
{
    private readonly IMapper _mapper;
    private readonly IRegionRepository _regionRepository;
    private readonly IWeatherRepository _weatherRepository;

    public DeleteWeathersCommandHandler(IMapper mapper, IWeatherRepository weatherRepository, IRegionRepository regionRepository)
    {
        _mapper = mapper;
        _weatherRepository = weatherRepository;
        _regionRepository = regionRepository;
    }

    public async Task Handle(DeleteWeathersCommandRequest request, CancellationToken cancellationToken)
    {
        var regionExists = await _regionRepository.AnyAsync(x => x.Id == request.RegionId, cancellationToken);
        if (regionExists == false) throw new NotFoundException($"Регион с id '{request.RegionId}' не найден");

        var weather = await _weatherRepository.FindAllAsync(x => x.Regions.Select(y => y.Id).Contains(request.RegionId), cancellationToken);

        await _weatherRepository.DeleteRangeAsync(weather, cancellationToken);
    }
}